package com.msh.frame.client.exception;

import com.msh.frame.client.common.ErrorCode;
import com.msh.frame.client.common.Result;

/**
 * 服务层产生的异常 构建异常时需提供Result对象
 */
public class BizException extends MshRuntimeException {

  private Result result;

  public Result getResult() {
    return result;
  }

  public BizException(Result result) {
    super(result.getMsg());
    this.result = result;
  }

  public BizException(String msg) {
    super(msg);
    this.result = Result.errorReturn(ErrorCode.REQUEST_ERROR.getCode(), msg);
  }

  public static BizException build(Result result){
    return new BizException(result);
  }

  public static BizException build(ErrorCode errorCode){
    return new BizException(Result.errorReturn(errorCode));
  }

  public static BizException build(String msg){
    return new BizException(Result.errorReturn(ErrorCode.BIZ_ERROR.getCode(), msg));
  }

  public static void doThrowIfTrue(String msg, boolean b) {
    doThrowIfTrue(Result.errorReturn(ErrorCode.REQUEST_ERROR.getCode(), msg), b);
  }

  public static void doThrowIfTrue(Result result, boolean b) {
    if (b) {
      throw new BizException(result);
    }
  }

  public static void doThrowIfTrue(ErrorCode errorCode, boolean b) {
    if (b) {
      throw new BizException(Result.errorReturn(errorCode));
    }
  }

  public static void doThrowIfNull(String msg, Object... o) {
    if(null == o){
      throw new BizException(Result.errorReturn(ErrorCode.REQUEST_ERROR.getCode(), msg));
    }
    for (Object obj : o) {
      if (null == obj) {
        throw new BizException(Result.errorReturn(ErrorCode.REQUEST_ERROR.getCode(), msg));
      }
    }
  }
}
